package cn.aylog.test;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DemoShiro {

    Logger LOG = LoggerFactory.getLogger(DemoShiro.class);

    @Test
    public void start() {
        LOG.info("开始加载配置文件");
        // 加载配置文件
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 获取管理实例
        SecurityManager securityManager = factory.getInstance();
        // 管理实例
        SecurityUtils.setSecurityManager(securityManager);
        // 获取subject
        Subject subject = SecurityUtils.getSubject();
        // 创建身份,凭证
        AuthenticationToken token = new UsernamePasswordToken("zhangsan", "zs");
        // 校验
        subject.login(token);
        System.out.println("登录成功");
        // 角色校验
        boolean role1 = subject.hasRole("role1");
        System.out.println(role1);
        try {
            // 权限校验
            subject.checkPermission("user:insert111");
        }catch (UnauthorizedException e) {
            LOG.debug("权限不足");
            System.out.println("权限不足");
        }

    }

    @Test
    public void myRealm() {
        LOG.info("开始加载配置文件");
        // 加载配置文件
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 获取管理实例
        SecurityManager securityManager = factory.getInstance();
        // 管理实例
        SecurityUtils.setSecurityManager(securityManager);
        // 获取subject
        Subject subject = SecurityUtils.getSubject();
        // 创建身份,凭证
        AuthenticationToken token = new UsernamePasswordToken("zhangsan11", "zs");
        // 校验 UnknownAccountException IncorrectCredentialsException
        try{
            subject.login(token);
            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
        }


    }

}
